-- UIBuyPuzzles
-- Created by huanghr
-- 购买冈布奥碎片界面

UIBuyPuzzles = class("UIBuyPuzzles", function()
    return cc.Layer:create();
end);

function UIBuyPuzzles.create(goodsId, priceType, goodsType)
    return UIBuyPuzzles.new(goodsId, priceType, goodsType);
end

-- 内部函数声明
local resize;

-- 构造函数
function UIBuyPuzzles:ctor(goodsId, priceType, goodsType)
    self:setName("UIBuyPuzzles");
    self.goodsId = goodsId;

    -- 初始化
    local node = cc.CSLoader:createNode("layout/item/BuyFood.csb");
    self:addChild(node);
    self.node = node;

    self.priceType = priceType;

    self.goodsType = goodsType;

    -- 更换背景底图
    local up1 = findChildByName(self.node, "CT/bg_type");
    local up2 = findChildByName(self.node, "CT/bg_type2")
    up1:loadTexture(getTitleBgIconPath("pet"));
    up2:loadTexture(getTitleBgIconPath("pet"))
    -- 注册事件处理回调函数
    self:registerEventCallback()

    -- 注册各种点击事件
    self:registerTouchEvent();

    -- 重绘
    self:redraw();

    -- 适配
    resize(node);
end

-- 注册点击事件
function UIBuyPuzzles:registerTouchEvent()
    local node = self.node;

    -- 注册返回按钮点击事件
    local btnBack = findChildByName(node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UIBuyPuzzles");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 购买个数
    local str = getLocStr("bulk_purchase");
    -- 注册确认购买按钮点击事件
    local btnBuy = findChildByName(self.node, "CT/price1_btn");
    local function onBuyClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");
            -- 尝试购买
            self:tryBuy(10);
        end
    end
    btnBuy:addTouchEventListener(onBuyClick);
    TextStyleM.setTextStyle(btnBuy, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBuy:setTitleText(string.format(str, 10));

    -- 注册确认购买按钮点击事件
    local btnBuy = findChildByName(self.node, "CT/price2_btn");
    local function onBuyClick2(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");
            -- 尝试购买
            self:tryBuy(1);
        end
    end
    btnBuy:addTouchEventListener(onBuyClick2);
    TextStyleM.setTextStyle(btnBuy, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBuy:setTitleText(string.format(str, 1));
end

-- 注册事件处理回调函数
function UIBuyPuzzles:registerEventCallback()
    self:registerScriptHandler(function(ev)
        if ev == "exit" then
            EventMgr.removeAll("UIBuyPuzzles");
            local uiPetShop = UIMgr.getCurrentScene():getFormByName("UIPetShop");
            if uiPetShop then
                uiPetShop:redraw();
            end
        elseif ev == "enter" then

        end
    end);

    -- 购买商品事件回调
    EventMgr.register("UIBuyPuzzles", event.BUY_PUZZLE_BOX, function(args)
        self:redraw();

        local classId = FormulaM.invoke("CALC_PUZZLE_BOX_COST_CLASS_ID", args.puzzleType);
        local name = ItemM.query(classId, "name");
        local lightNode2 = findChildByName(self.node, "CT/item/bg");
        lightNode2:removeAllChildren();

        -- 弹字提示
        local list = {string.format(getLocStr("buy_goods_done"), name, args.amount), };
        local limitCount = ServerStatusM.query("golden_pot_buy_limit") or 0;
        limitCount = FormulaM.invoke("CALC_GOLDEN_POT_BUY_LIMIT", limitCount);
        if limitCount > 0 then
            table.insert(list, string.format(getLocStr("left_can_buy_times"), self:leftCanBuyNum()));
        end
        splitAlert(list, 0.8);

        if type(args.amount) == "number" and args.amount > 1 then
            playEffect(lightNode2, 1231, 93, 9,  nil, 0.82);
        else
            playEffect(lightNode2, 1180, 93, 9,  nil, 0.82);
        end
    end);

    -- 购买商品事件回调
    EventMgr.register("UIBuyPuzzles", event.BUY_HERO_RELIC, function(args)
        self:redraw();

        local lightNode2 = findChildByName(self.node, "CT/item/bg");
        lightNode2:removeAllChildren();

        if type(args.amount) == "number" and args.amount > 1 then
            playEffect(lightNode2, 1231, 93, 9,  nil, 0.82);
        else
            playEffect(lightNode2, 1180, 93, 9,  nil, 0.82);
        end
    end);

    -- 关注服务器状态更新
    EventMgr.register("UIBuyPuzzles", event.SERVER_STATUS_UPDATE, function(para)
        local data = para.data;
        if data["golden_pot_buy_limit"] then
            self:redraw();
        end
    end);
end

-- 剩余可以购买数量
function UIBuyPuzzles:leftCanBuyNum()
    -- 判断是否限制了次数
    local limitCount = ServerStatusM.query("golden_pot_buy_limit") or 0;
    limitCount = FormulaM.invoke("CALC_GOLDEN_POT_BUY_LIMIT", limitCount);
    local leftNum = 10;
    if limitCount > 0 and self.goodsType ~= "hero_relic" then
        local dailyOperationLimit = ME.user.dbase:query("daily_operation_limit", {});
        local operationCount = dailyOperationLimit["operation_count"] or {};
        -- 剩余可以购买数量
        if self.priceType == "gem" then
            leftNum = limitCount - tonumber(operationCount["golden_pot_buy"]);
        else
            leftNum = limitCount - tonumber(operationCount["normal_pot_buy"]);
        end
    end

    return leftNum;
end

-- 重绘
function UIBuyPuzzles:redraw()
    -- 显示商品名称
    local CT = findChildByName(self.node, "CT");
    local nameLabel = CT:getChildByName("title");
    local subHeadLabel = findChildByName(self.node, "CT/subhead");

    -- 获取商品信息
    local itemName = ItemM.query(self.goodsId, "name");
    nameLabel:setString(itemName);
    TextStyleM.setTitleStyle(nameLabel);

    -- 先停止滚动
    if self.scrollingData and self.scrollingData.classId ~= self.classId then
        stopScrolling(subHeadLabel);
    end

    -- 当前拥有的数量
    TextStyleM.setSubheadStyle(subHeadLabel);
    local curAmount = ItemM.getAmount(ME.user, self.goodsId);
    local scrollingData = self.scrollingData;

    -- 没有滚动过
    if not scrollingData or scrollingData.classId ~= self.goodsId then
        subHeadLabel:setString(string.format(getLocStr("own_num"), ItemM.getAmount(ME.user, self.goodsId)));
        self.scrollingData = {
            ["lastAmount"] = curAmount,
            ["classId"]    = self.goodsId,
        };
    else
        -- 滚动
        numScrolling(subHeadLabel, getLocStr("own_num"), scrollingData.lastAmount, curAmount, 30);

        scrollingData.lastAmount = curAmount;
    end

    -- 显示商品价格
    local priceNode1 = findChildByName(self.node, "CT/price1");
    local priceNode2 = findChildByName(self.node, "CT/price2");

    -- 宝石盒花费
    local cost = FormulaM.invoke("CALC_PUZZLE_BOX_COST", self.priceType);
    local attrib = cost[2];
    local value  = cost[3];

    if self.goodsType == "hero_relic" then
        local sellPrice = ItemM.query(self.goodsId, "sell_price");
        local cost = sellPrice[1];
        value  = cost[3];
    end

    local priceLabel1 = findChildByName(priceNode1, "price_label");

    -- 购买十个的价格
    TextStyleM.setTextStyle(priceLabel1, TextStyleM.TEXT_SIZE_MINI, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true, getLocKerning() - 2);
    priceLabel1:setString(tostring(value * 10));

    -- 购买一个时的价格
    local priceLabel2 = findChildByName(priceNode2, "price_label");
    TextStyleM.setTextStyle(priceLabel2, TextStyleM.TEXT_SIZE_MINI, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true, getLocKerning() - 2);
    priceLabel2:setString(tostring(value));

    if not self.pricePosX then
        self.pricePosX = priceLabel1:getPositionX();
    end

    if self.priceType ~= "gem" then
        -- 整体右移
        priceLabel1:setPositionX(self.pricePosX + 5);
        priceLabel2:setPositionX(self.pricePosX + 5);
    end

    -- 剩余可以购买数量
    local leftNum = self:leftCanBuyNum();

    -- 获取金钱
    -- 获取当前用户的金币数量
    local btnBuy1 = findChildByName(self.node, "CT/price1_btn");
    local btnBuy2 = findChildByName(self.node, "CT/price2_btn");

    local gemCount = ME.user:queryAttrib(self.priceType);
    if gemCount >= value * 10 then
        TextStyleM.setTextStyle(priceLabel1, TextStyleM.TEXT_SIZE_MINI, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true, getLocKerning() - 2);
        if leftNum >= 10 then
            btnBuy1:setBright(true);
            btnBuy1:setTouchEnabled(true);
        else
            btnBuy1:setBright(false);
            btnBuy1:setTouchEnabled(false);
        end
    else
        TextStyleM.setTextStyle(priceLabel1, TextStyleM.TEXT_SIZE_MINI, TextStyleM.TEXT_COLOR_LIGHT_RED, true, getLocKerning() - 2);
        btnBuy1:setBright(false);
        btnBuy1:setTouchEnabled(false);
    end

    if gemCount >= value then
        TextStyleM.setTextStyle(priceLabel2, TextStyleM.TEXT_SIZE_MINI, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true, getLocKerning() - 2);
        if leftNum >= 1 then
            btnBuy2:setBright(true);
            btnBuy2:setTouchEnabled(true);
        else
            btnBuy2:setBright(false);
            btnBuy2:setTouchEnabled(false);
        end
    else
        TextStyleM.setTextStyle(priceLabel2, TextStyleM.TEXT_SIZE_MINI, TextStyleM.TEXT_COLOR_LIGHT_RED, true, getLocKerning() - 2);
        btnBuy2:setBright(false);
        btnBuy2:setTouchEnabled(false);
    end

    local priceBg1 = findChildByName(priceNode1, "price_bg");
    local priceBg2 = findChildByName(priceNode2, "price_bg");

    local gemBg1 = findChildByName(priceNode1, "gem_bg");
    local gemBg2 = findChildByName(priceNode2, "gem_bg");

    -- 显示价格对应的背景
    if attrib == "gem" then
        priceBg1:setVisible(false);
        priceBg2:setVisible(false);
        gemBg1:setVisible(true);
        gemBg2:setVisible(true);
    else
        priceBg1:setVisible(true);
        priceBg2:setVisible(true);
        gemBg1:setVisible(false);
        gemBg2:setVisible(false);
    end

    -- 物品图标
    local item = findChildByName(self.node, "CT/item");

    -- 物品图标
    local iconImg = findChildByName(item, "icon");
    iconImg:loadTexture(getItemIconPath(ItemM.query(self.goodsId, "icon")));
    if not self.PosY then
        self.PosY = iconImg:getPositionY();
    end

    if self.goodsType == "hero_relic" then
        iconImg:setPositionY(self.PosY + 4);
    end

    -- 物品星级
    local starNode = findChildByName(item, "star_node");
    local rank = ItemM.query(self.goodsId, "rank");
    local layer = createStarLayer(rank, "images/ui/symbol/star_little.png", "center", -0.7);
    if layer then
        starNode:removeAllChildren();
        starNode:addChild(layer);
    end
    starNode:setVisible(false);

    -- 物品的背景框
    local frameImage = findChildByName(item, "bg");
    frameImage:loadTexture(getFrameBgIconPath("rank", 1));
end

-- 适配
function resize(node)
    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 尝试购买
function UIBuyPuzzles:tryBuy(amount)
    if self.goodsType ~= "hero_relic" then
        local ret = PetShopM.canBuyPuzzleBox(self.priceType, amount);
        if true ~= ret then
            local leftNum = self:leftCanBuyNum();
            if leftNum < amount then
                -- alert(string.format(getLocStr("left_can_buy_times"), self:leftCanBuyNum()));
                return;
            end

            if self.priceType == "gem" then
                -- 钻石不足
                showGemLackConfirm();
            else
                -- 其他原因，统一提示失败
                trace("UIBuyPuzzles", "金钱不足，购买失败");
                showHint(getLocStr("not_enough_money"));
            end
            return;
        end


        -- 购买
        Operation.cmd_buy_puzzle_box(self.priceType, amount);
    else
        local ret = ArtifactM.canBuyHeroRelic(self.goodsId, amount);
        if true ~= ret then
            trace("UIBuyPuzzles", "金钱不足，购买失败");
            showHint(getLocStr("not_enough_money"));
            return;
        end

        Operation.cmd_buy_hero_relic(self.goodsId, amount);
    end
end